import socket
from cryptography.fernet import Fernet

# 必须与服务端使用相同密钥
key = b'pRmgMa8T0INjEAfksaq2aafzoZXEuwKIvDCD8gZW8ek='
cipher = Fernet(key)


def send_file(host):
    port = 12345

    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        s.connect((host, port))

        # 读取并发送文件
        try:
            with open('client_input.txt', 'rb') as f:
                file_data = f.read()

            encrypted_data = cipher.encrypt(file_data)
            s.send(len(encrypted_data).to_bytes(4, byteorder='big'))
            s.sendall(encrypted_data)
            print(f"已发送 {len(file_data)} 字节原始数据")

            # 接收回复
            resp_len = int.from_bytes(s.recv(4), byteorder='big')
            encrypted_resp = s.recv(resp_len)
            decrypted_resp = cipher.decrypt(encrypted_resp)

            with open('client_response.txt', 'wb') as f:
                f.write(decrypted_resp)
            print(f"已接收 {len(decrypted_resp)} 字节回复数据")

        except FileNotFoundError:
            print("错误：未找到输入文件")


if __name__ == '__main__':
    server_ip = input("请输入服务端IP地址: ")
    send_file(server_ip)